package com.fmi.cloud.biz;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.fmi.cloud.R;
import com.fmi.cloud.download.FileDownloader;
import com.fmi.cloud.util.SystemInfoUtil;
import com.fmi.cloud.util.YcToastHelper;
import com.fmi.cloud.view.NewConfirmDialog;
import com.fmi.cloud.view.NumberProgressBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * 版本升级
 * <p>
 * Created by zv on 2017-12-12.
 */

public class VersionUtil {

    private Context mContext;
    private String apkURL = "";
    private String isForce = "";

    public VersionUtil(Context context) {
        this.mContext = context;
    }

    public void handleVersion(Map<String, Object> map) {
        String version = String.valueOf(map.get("version"));
        String minVersion = String.valueOf(map.get("minVersion"));
        apkURL = String.valueOf(map.get("url"));
        isForce = String.valueOf(map.get("isForce"));
        String versionInfo = String.valueOf(map.get("remark"));
        String localVersion = SystemInfoUtil.getVersionName(mContext);
        boolean hasNew = hasNew(version, localVersion);
        if (hasNew) {
            if (isForce.equals("1")) {
                showNoticeDialog(1, version, versionInfo);
            } else if (isForce.equals("2")) {
                showNoticeDialog(2, version, versionInfo);
            } else {
                showNoticeDialog(0, version, versionInfo);
            }
        }
    }

    private void showNoticeDialog(final int isForce, String newVersion, final String info) {
        final NewConfirmDialog confirmDialog;
//        String updateSize = FileDownloader.getDownloadSize(apkURL);
        if (isForce == 1 || isForce == 2) {
            confirmDialog = new NewConfirmDialog(null, mContext, "发现新版本！(" + newVersion + ")", info, null, "下载更新");
            confirmDialog.setCancelable(false);
        } else {
            confirmDialog = new NewConfirmDialog(null, mContext, "发现新版本！(" + newVersion + ")", info, "取消", "下载更新");
        }

        NewConfirmDialog.ClickListenerInterface listener = new NewConfirmDialog.ClickListenerInterface() {
            @Override
            public void doLeft() {
                confirmDialog.dismiss();
            }

            @Override
            public void doRight() {
                confirmDialog.dismiss();
                if (!android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {
                    YcToastHelper.getInstance()._toast("请检查是否存在sd卡");
                    return;
                }
//                createNotification();
                if (isForce != 0) {
                    initProgressDialog();
                } else {
                    YcToastHelper.getInstance()._toast("正在后台下载最新版本，可在任务栏中查看进度。");
                }
                downloadAPK();
            }
        };

        confirmDialog.setClicklistener(listener);
        if (mContext != null) {
            if (!((Activity) mContext).isFinishing()) {
                confirmDialog.show();
            }
        }

    }

    private Dialog dialog = null;

    private void initProgressDialog() {
        if (mContext != null) {
            if (!((Activity) mContext).isFinishing()) {
                final LayoutInflater inflater = LayoutInflater.from(mContext);
                View v = inflater.inflate(R.layout.progress, null);
                NumberProgressBar progressBar = (NumberProgressBar) v.findViewById(R.id.numberbar);
                progressBar.setMax(100);
                dialog = new Dialog(mContext, R.style.NewUIAlertViewStyle);
                dialog.setContentView(v);
                dialog.setCancelable(false);
                dialog.show();
            }
        }
    }

    private boolean hasNew(String newVersion, String oldVersion) {
        boolean hasNew = false;
        try {
            String[] newVer = newVersion.split("\\.");
            String[] oldVer = oldVersion.split("\\.");
            if (newVer.length == oldVer.length) {
                for (int i = 0; i < newVer.length; i++) {//长度不同,表示数据变了,直接判断为有新版本,同时避免数组越界
                    if (newVer[i].compareTo(oldVer[i]) > 0) {
                        hasNew = true;
                        break;
                    }
                }
            }

        } catch (Exception e) {
            Log.e("VersionUtil", e.getMessage());
        }
        return hasNew;
    }

    /* 下载包安装路径 */
    private String savePath = Environment.getExternalStorageDirectory().getPath() + "/fangmi/";
    private String saveFileName = savePath + "fangmi.apk";
    private static final int DOWN_OK = 1;
    private static final int DOWN_ERROR = 0;

    private void downloadAPK() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int down_step = 3;// 提示step
                    int downloadCount = 0;// 已经下载好的大小
                    int updateCount = 0;// 已经上传的文件大小
                    URL url = new URL(apkURL);

                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setRequestProperty("Accept-Encoding", "identity");
                    conn.connect();
                    int totalSize = conn.getContentLength();// 文件总大小
                    InputStream inputStream = conn.getInputStream();

                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    String apkFile = saveFileName;
                    File ApkFile = new File(apkFile);
                    FileOutputStream outputStream = new FileOutputStream(ApkFile);

                    byte buffer[] = new byte[1024];
                    int readsize = 0;
                    while ((readsize = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, readsize);
                        downloadCount += readsize;// 时时获取下载到的大小
                        int hasLoaded = downloadCount * 100 / totalSize;
                        int fenmu = updateCount;
                        boolean iscontinue = hasLoaded >= fenmu;
                        /* 每次增张3%*/
                        if (updateCount == 0 || hasLoaded - down_step >= updateCount) {
                            updateCount += down_step;
                            // 改变通知栏与弹出进度条
//                            notifyBar(updateCount);
                        }
                    }
//                    notifyBar(100);
                    outputStream.close();
                    inputStream.close();
                    if (downloadCount >= totalSize) {
                        Message message = new Message();
                        message.what = DOWN_OK;
                        handler.sendMessage(message);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = DOWN_ERROR;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = DOWN_ERROR;
                    handler.sendMessage(message);
                }
            }
        }).start();
    }

    private final Handler handler = new Handler() {
        @Override

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_OK:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    if (!isForce.equals("0")) {
                        if (mContext != null) {
                            if (!((Activity) mContext).isFinishing()) {
                                final NewConfirmDialog newConfirmDialog =
                                        new NewConfirmDialog(mContext, "更新完成",
                                                "更新完成", "确定");
                                newConfirmDialog.setCancelable(false);
                                NewConfirmDialog.ClickListenerInterface listener =
                                        new NewConfirmDialog.ClickListenerInterface() {
                                            @Override
                                            public void doLeft() {

                                            }

                                            @Override
                                            public void doRight() {
                                                newConfirmDialog.dismiss();
                                                installApk();
                                            }
                                        };
                                newConfirmDialog.setClicklistener(listener);
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        newConfirmDialog.show();
                                    }
                                });
                            }
                        } else {
                            installApk();
                        }
                    } else {
                        installApk();
                    }
                    break;

                case DOWN_ERROR:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    YcToastHelper.getInstance()._toast("下载失败，请稍后重试");
                    break;

                default:

                    break;
            }
        }
    };

    private void installApk() {
        File file = new File(saveFileName);
        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

}
